﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace InspectionMAC.Config
{
    public static class ProductSampleTracker
    {
        // 样本ID队列（FIFO处理）
        private static readonly ConcurrentQueue<string> _sampleQueue = new ConcurrentQueue<string>();

        // 当前活跃样本及其到达时间
        private static readonly Dictionary<string, DateTime> _activeSamples = new Dictionary<string, DateTime>();

        // 超时设置（毫秒）
        private const int SAMPLE_TIMEOUT = 300000; // 5分钟

        /// <summary>
        /// 注册新样本进入系统
        /// </summary>
        public static string RegisterNewSample()
        {
            // 生成唯一样本ID（时间戳 + 计数器）
            string sampleId = $"{DateTime.Now:yyyyMMddHHmmssfff}_{Guid.NewGuid().ToString("N").Substring(0, 4)}";

            lock (_sampleQueue)
            {
                _sampleQueue.Enqueue(sampleId);
                _activeSamples[sampleId] = DateTime.Now;
                Console.WriteLine($"新样本注册: {sampleId}");
                return sampleId;
            }
        }

        /// <summary>
        /// 获取下一个需要处理的样本ID
        /// </summary>
        public static string GetNextSampleId()
        {
            lock (_sampleQueue)
            {
                if (_sampleQueue.TryPeek(out string sampleId))
                {
                    // 检查样本是否超时
                    if ((DateTime.Now - _activeSamples[sampleId]).TotalMilliseconds > SAMPLE_TIMEOUT)
                    {
                        _sampleQueue.TryDequeue(out string expiredId);
                        Console.WriteLine($"样本超时移除: {expiredId}");
                        return null;
                    }
                    return sampleId;
                }
                return null;
            }
        }

        /// <summary>
        /// 标记样本已完成处理
        /// </summary>
        public static void MarkSampleCompleted(string sampleId)
        {
            lock (_sampleQueue)
            {
                if (_sampleQueue.TryPeek(out string currentId) && currentId == sampleId)
                {
                    _sampleQueue.TryDequeue(out string completedId);
                    _activeSamples.Remove(completedId);
                    Console.WriteLine($"样本完成: {completedId}");
                }
                else
                {
                    Console.WriteLine($"警告: 尝试完成的样本不在队列头部: {sampleId}");
                }
            }
        }
    }
}
